<template>
  <div class="container">
    <!-- 播放控制区域 -->
    <div class="player">
      <el-button
        type="primary"
        :icon="isPlaying ? VideoPause : VideoPlay"
        @click="togglePlay"
        circle
      />
      <audio ref="audioRef" :src="audioUrl"></audio>
    </div>

    <!-- 答案选项区域 -->
    <div class="options">
      <el-card
        v-for="item in options"
        :key="item.id"
        class="option-card"
        @click="handleSelect(item)"
        shadow="hover"
      >
        <el-image :src="item.image" fit="cover" class="option-image" />
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onBeforeUnmount } from 'vue'
import { VideoPlay, VideoPause } from '@element-plus/icons-vue'
import { ElMessage, ElButton, ElImage, ElCard } from 'element-plus'

// 类型定义
interface OptionItem {
  id: number
  image: string
  answer: string
}

// 音频控制
const audioRef = ref<HTMLAudioElement | null>(null)
const isPlaying = ref(false)
const timestamp = ref(Date.now())

// 带时间戳的音频URL
const audioUrl = computed(() => `/apple-1.mp3?t=${timestamp.value}`)

// 当音频源变化时重新绑定监听
watch(audioUrl, () => {
  nextTick(() => {
    const cleanup = setupAudioListeners()
    onBeforeUnmount(cleanup)
  })
})

const togglePlay = async () => {
  if (!audioRef.value) return

  try {
    console.log('开始播放')
    if (isPlaying.value) {
      audioRef.value.pause()
    } else {
      // 重置播放进度
      audioRef.value.currentTime = 0
      await audioRef.value.play()
    }
    isPlaying.value = !isPlaying.value
    console.log('结束播放')
  } catch (error) {
    console.error('播放失败:', error)
    // 强制刷新音频源
    timestamp.value = Date.now()
  }
}

// 添加音频事件监听
const setupAudioListeners = () => {
  if (!audioRef.value) return

  // 播放结束回调
  const handleEnded = () => {
    isPlaying.value = false
  }

  // 添加事件监听
  audioRef.value.addEventListener('ended', handleEnded)

  // 返回清理函数
  return () => {
    audioRef.value?.removeEventListener('ended', handleEnded)
  }
}

// 组件挂载时设置监听
onMounted(() => {
  const cleanup = setupAudioListeners()

  // 组件卸载时清理
  onBeforeUnmount(() => {
    cleanup?.()
  })
})

// 答案选项数据
const options = ref<OptionItem[]>([
  {
    id: 1,
    image: '/peach.jpg',
    answer: 'A',
  },
  {
    id: 2,
    image: '/apple.jpg',
    answer: 'B',
  },
])

// 选项选择处理
const handleSelect = (item: OptionItem) => {
  console.log('已选择答案:', item.answer)
  // 这里可以添加答案处理逻辑
  // 添加答案验证逻辑
  const correctAnswer = 'B' // 假设正确答案是 B

  if (item.answer === correctAnswer) {
    ElMessage.success({
      message: '🎉 回答正确！',
      duration: 1000, // 2秒后自动关闭
      showClose: true,
    })
  } else {
    ElMessage.error({
      message: '❌ 答案错误，请再试一次',
      duration: 1000,
      showClose: true,
    })
  }
}
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.player {
  margin-bottom: 3rem;
}

.player .el-button {
  width: 60px;
  height: 60px;
}

.options {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.option-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.option-card:hover {
  transform: translateY(-5px);
}

.option-image {
  width: 100%;
  height: 50px;
}
</style>
